package com.scau.hwadee.examination.utils;


import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author: YHX
 * @Date: 2019/7/4 14:08
 * 用来产生24位或者32位不重复id的工具类用来作为表的主键id
 */
public interface Generator {

    /**
     * 产生一个唯一的ID值
     * @return
     */
    String generatorId();

    /**
     * 1.内部类默认是public static
     * 2.产生32位不重复的id
     */
    class UUIDGenerator implements Generator {
        public UUIDGenerator() {
        }

        @Override
        public synchronized String generatorId() {
            return UUID.randomUUID().toString().replace("-", "");
        }
    }

    /**
     *  这个方法就是用ipv4的地址来产生不同的id
     *  1.先获取电脑的ipv4地址，注意是ipv4地址，ipv6地址好像有点难搞，格式那些不好解决，ipv4就全部都是
     *  数字，好解决
     *  2.再随便加个长度和一个线程安全的自增数
     *  3.产生唯一的id值
     */
    class GlobalGenerator implements Generator {
        private String seed;
        private final AtomicLong sequence = new AtomicLong(1L);
        private int length;

        public GlobalGenerator() {
            try {
                this.seed = LocalUtils.getLocalHost() + "-" + System.currentTimeMillis() + "-";
                this.length = this.seed.length() + "9223372036854775807".length();
            } catch (Exception var2) {
                throw new RuntimeException(var2);
            }
        }

        @Override
        public synchronized String generatorId() {
            StringBuilder sb = new StringBuilder(this.length);
            sb.append(this.seed);
            sb.append(this.sequence.getAndIncrement());
            String result = sb.toString();
            result = result.replace(':', '-');
            result = result.replace('_', '-');
            result = result.replace('.', '-');
            return result.replace("-", "");
        }

        public static void main(String[] args) {
            Generator.GlobalGenerator g=new Generator.GlobalGenerator();
            System.out.println(g.generatorId().length());
        }
    }
}
